use RRDs;

$root = '/var/lib/smokeping/';
#@isp = ('TEL-v', 'CNC-v','ziyuanbu');
@isp = ('Telecom', 'Netcom','ShuangXian');
foreach $isp (@isp) {
        @rtt = @loss = ();
        while ($rrd = glob "$root/$isp/*") {
                if ($rrd =~ /\/([^\/]+)\.rrd$/) {
                        $area = $1;
                } else {
                        next;
                }

                $loss_min = $loss_max = $loss_sum = $loss_cnt = 0;
                $rtt_min = $rtt_max = $rtt_sum = $rtt_cnt = 0;

                ($start, $step, $names, $data) = RRDs::fetch($rrd, 'AVERAGE');
                foreach $row (@$data) {
                        ($uptime, $loss, $median, @pings) = @$row;
                        next unless defined($median);

                        $rtt_max = $median if ($median > $rtt_max);
                        $rtt_min = $median if ($rtt_min == 0 or $median < $rtt_min);
                        $rtt_sum += $median;
                        $rtt_cnt++;

                        $loss_max = $loss if ($loss > $loss_max);
                        $loss_min = $loss if ($loss_min == 0 or $loss < $loss_min);
                        $loss_sum += $loss;
                        $loss_cnt++;
                }

                if ($rtt_cnt == 0) {
                        push @rtt, sprintf("%s;;;\n", $area);
                } else {
                        push @rtt, sprintf("%s;%.2f;%.2f;%.2f\n", $area, 1000 * $rtt_min, 1000 * $rtt_sum / $rtt_cnt, 1000 * $rtt_max);
                }
                if ($loss_cnt == 0) {
                        push @loss, sprintf("%s;;;\n", $area);
                } else {
                        push @loss, sprintf("%s;%.2f;%.2f;%.2f\n", $area, 5 * $loss_min, 5 * $loss_sum / $loss_cnt, 5 * $loss_max);
                }
        }

        print "RTT(ms)\n";
        print "$isp;MIN;AVG;MAX\n";
        print @rtt, "\n";

        print "LOSS(%)\n";
        print "$isp;MIN;AVG;MAX\n";
        print @loss, "\n";
}
